package com.uwlaser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.uwlaser.base.CommonTree;
import com.uwlaser.base.PageInfo;
import com.uwlaser.base.QueryHelpMybatisPlus;
import com.uwlaser.base.impl.CommonServiceImpl;
import com.uwlaser.domain.ProductBom;
import com.uwlaser.domain.ProductBomDetail;
import com.uwlaser.domain.ProductMaterial;
import com.uwlaser.domain.ProductModel;
import com.uwlaser.exception.EntityExistException;
import com.uwlaser.service.ProductBomService;
import com.uwlaser.service.dto.ProductBomDto;
import com.uwlaser.service.dto.ProductBomQueryParam;
import com.uwlaser.service.mapper.ProductBomDetailMapper;
import com.uwlaser.service.mapper.ProductBomMapper;
import com.uwlaser.service.mapper.ProductMaterialMapper;
import com.uwlaser.service.mapper.ProductModelMapper;
import com.uwlaser.utils.ConvertUtil;
import com.uwlaser.utils.PageUtil;
import com.uwlaser.utils.enums.DictValueEnum;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
* @author zk-Qin
* @date 2022-05-11
*/
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = ProductBomService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ProductBomServiceImpl extends CommonServiceImpl<ProductBomMapper, ProductBom> implements ProductBomService {

    // private final RedisUtils redisUtils;
    private final ProductBomMapper productBomMapper;

    private final ProductBomDetailMapper productBomDetailMapper;

    private final ProductModelMapper productModelMapper;

    private final ProductMaterialMapper productMaterialMapper;

    @Override
    public PageInfo<ProductBomDto> queryAll(ProductBomQueryParam query, Pageable pageable) {
        IPage<ProductBom> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<ProductBom> page = productBomMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, ProductBomDto.class);
    }

    @Override
    public List<ProductBomDto> queryAll(ProductBomQueryParam query){
        return ConvertUtil.convertList(productBomMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), ProductBomDto.class);
    }

    @Override
    public ProductBom getById(Integer id) {
        return productBomMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public ProductBomDto findById(Integer id) {
        return ConvertUtil.convert(getById(id), ProductBomDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(ProductBomDto resources) {
        ProductBom entity = ConvertUtil.convert(resources, ProductBom.class);
        checkValidation(entity);
        return productBomMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(ProductBomDto resources){
        ProductBom entity = ConvertUtil.convert(resources, ProductBom.class);
        checkValidation(entity);
        int ret = productBomMapper.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    /**
     * 校验有效性：
     * 1. 编号&版本 做唯一性判断
     * 2. 产品号&是否禁用 做单产品唯一性判断
     * @param entity ProductBom
     */
    private void checkValidation(ProductBom entity) {
        if (DictValueEnum.START.getValue().equals(entity.getIsDisable())) {
            ProductBomQueryParam param = new ProductBomQueryParam();
            param.setIsDisable(entity.getIsDisable());
            param.setProductCode(entity.getProductCode());
            List<ProductBom> boms = productBomMapper.selectList(QueryHelpMybatisPlus.getPredicate(param));
            if (boms != null && !boms.isEmpty()) {
                if (entity.getId() == null) {
                    throw new EntityExistException(ProductBom.class, "产品型号", entity.getProductCode());
                } else {
                    for (ProductBom bom : boms) {
                        if (!entity.getId().equals(bom.getId())) {
                            throw new EntityExistException(ProductBom.class, "产品型号", entity.getProductCode());
                        }
                    }
                }
            }
        }
        ProductBomQueryParam param = new ProductBomQueryParam();
        param.setVersion(entity.getVersion());
        param.setBomCode(entity.getBomCode());
        List<ProductBom> boms = productBomMapper.selectList(QueryHelpMybatisPlus.getPredicate(param));
        if (boms != null && !boms.isEmpty()) {
            if (entity.getId() == null) {
                throw new EntityExistException(ProductBom.class, "BOM编码 & 版本", entity.getBomCode() + " & "
                        + entity.getVersion());
            } else {
                for (ProductBom bom : boms) {
                    if (!entity.getId().equals(bom.getId())) {
                        throw new EntityExistException(ProductBom.class, "BOM编码 & 版本", entity.getBomCode() + " & "
                                + entity.getVersion());
                    }
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<Integer> ids){
        // delCaches(ids);
        return productBomMapper.deleteBatchIds(ids);
    }

    @Override
    public List<CommonTree> getBomTree(ProductBomQueryParam query) {

        ProductBom entity = productBomMapper.selectById(query.getId());

        List<CommonTree> commonTrees = new ArrayList<>();
        CommonTree commonTree = new CommonTree();
        //获取所有产品
        List<ProductModel> productModels = productModelMapper.selectList(null);
        if(productModels == null || productModels.size() == 0){
            return commonTrees;
        }
        Map<String, ProductModel> productMap = new HashMap<>();
        for (ProductModel productModel : productModels) {
            productMap.put(productModel.getMaterialCode(),productModel);
        }

        //获取所有物料
        List<ProductMaterial> materials = productMaterialMapper.selectList(null);
        Map<String, String> materialMap = new HashMap<>();
        if(materials != null && materials.size() > 0){
            for (ProductMaterial material : materials) {
                materialMap.put(material.getMaterialCode(),material.getMaterialName());
            }
        }
        createTree(entity,commonTree,productMap,materialMap);

        commonTree.setLabel(entity.getBomName());
        commonTree.setCode(entity.getBomCode());
        commonTrees.add(commonTree);

        return commonTrees;
    }

    public void createTree(ProductBom query, CommonTree commonTree, Map<String, ProductModel> productMap ,Map<String, String> materialMap ){
        //获取Bom明细
        ProductBomDetail productBomDetail = new ProductBomDetail();
        productBomDetail.setBomId(query.getId());
        List<ProductBomDetail> details = productBomDetailMapper.selectList(new QueryWrapper<>(productBomDetail));
        if(details == null || details.size() == 0){
            return ;
        }
        for (ProductBomDetail detail : details) {
            ProductModel productModel = productMap.get(detail.getMaterialCode());
            CommonTree children = new CommonTree();

            if(productModel != null){
                ProductBom productBom = new ProductBom();
                productBom.setProductCode(productModel.getProductCode());
                productBom.setIsDisable(DictValueEnum.START.getValue());
                ProductBom bom = productBomMapper.selectOne(new QueryWrapper<>(productBom));
                if(bom != null){
                    //递归获取
                    createTree(bom,children,productMap,materialMap);
                }
            }
            String leable = materialMap.get(detail.getMaterialCode()) == null ? detail.getMaterialCode() : materialMap.get(detail.getMaterialCode());
            children.setCode(detail.getMaterialCode());
            children.setLabel( leable );
            children.setId(detail.getId());
            children.setType(detail.getQuantity().toString());
            List<CommonTree> childrens = commonTree.getChildren();
            if(childrens == null){
                childrens = new ArrayList<>();
            }
            childrens.add(children);
            commonTree.setChildren(childrens);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Integer id){
        Set<Integer> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /*
    private void delCaches(Integer id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Integer> ids) {
        for (Integer id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<ProductBomDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (ProductBomDto productBom : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("BOM编号", productBom.getBomCode());
              map.put("BOM名称", productBom.getBomName());
              map.put("产品ID", productBom.getProductCode());
              map.put("是否禁用 ", productBom.getIsDisable());
              map.put("版本", productBom.getVersion());
              map.put("关联的物料", productBom.getMaterialCode());
              map.put("描述", productBom.getRemark());
              map.put("创建人", productBom.getCreateBy());
              map.put("创建时间", productBom.getCreateTime());
              map.put("更新人", productBom.getUpdateBy());
              map.put("更新时间", productBom.getUpdateTime());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/
}
